﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BST250301TestStand.Models.Helpers
{
    public class CSV
    {
        //读CSV文件类,读取指定的CSV文件，可以导出DataTable
        private ArrayList rowAL;         //行链表,CSV文件的每一行就是一个链
        private string fileName;        //文件名

        private Encoding encoding;        //编码
        static ReaderWriterLockSlim LogWriteLock = new ReaderWriterLockSlim();

        public CSV()
        {
            this.rowAL = new ArrayList();
            this.fileName = "";
            this.encoding = Encoding.Default;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="fileName">文件名,包括文件路径</param>
        public CSV(string fileName)
        {
            this.rowAL = new ArrayList();
            this.fileName = fileName;
            this.encoding = Encoding.Default;
            LoadCsvFile();
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="fileName">文件名,包括文件路径</param>
        /// <param name="encoding">文件编码</param>
        public CSV(string fileName, Encoding encoding)
        {
            this.rowAL = new ArrayList();
            this.fileName = fileName;
            this.encoding = encoding;
            LoadCsvFile();
        }

        /// <summary>
        /// 文件名,包括文件路径
        /// </summary>
        public string FileName
        {
            set
            {
                this.fileName = value;
                LoadCsvFile();
            }
        }

        /// <summary>
        /// 文件编码
        /// </summary>

        public Encoding FileEncoding
        {
            set
            {
                this.encoding = value;
            }
        }

        /// <summary>
        /// 获取行数
        /// </summary>
        public int RowCount
        {
            get
            {
                return this.rowAL.Count;
            }
        }

        /// <summary>
        /// 获取列数
        /// </summary>
        public int ColCount
        {
            get
            {
                int maxCol;

                maxCol = 0;
                for (int i = 0; i < this.rowAL.Count; i++)
                {
                    ArrayList colAL = (ArrayList)this.rowAL[i];

                    maxCol = (maxCol > colAL.Count) ? maxCol : colAL.Count;
                }

                return maxCol;
            }
        }


        /// <summary>
        /// 获取某行某列的数据

        /// row:行,row = 1代表第一行

        /// col:列,col = 1代表第一列  
        /// </summary>
        public string this[int row, int col]
        {
            get
            {
                //数据有效性验证

                CheckRowValid(row);
                CheckColValid(col);
                ArrayList colAL = (ArrayList)this.rowAL[row - 1];

                //如果请求列数据大于当前行的列时,返回空值

                if (colAL.Count < col)
                {
                    return "";
                }

                return colAL[col - 1].ToString();
            }
        }


        /// <summary>
        /// 根据最小行，最大行，最小列，最大列，来生成一个DataTable类型的数据

        /// 行等于1代表第一行

        /// 列等于1代表第一列

        /// maxrow: -1代表最大行
        /// maxcol: -1代表最大列
        /// </summary>
        public DataTable this[int minRow, int maxRow, int minCol, int maxCol]
        {
            get
            {
                //数据有效性验证

                CheckRowValid(minRow);
                CheckMaxRowValid(maxRow);
                CheckColValid(minCol);
                CheckMaxColValid(maxCol);
                if (maxRow == -1)
                {
                    maxRow = RowCount;
                }
                if (maxCol == -1)
                {
                    maxCol = ColCount;
                }
                if (maxRow < minRow)
                {
                    throw new Exception("最大行数不能小于最小行数");
                }
                if (maxCol < minCol)
                {
                    throw new Exception("最大列数不能小于最小列数");
                }
                DataTable csvDT = new DataTable();
                int i;
                int col;
                int row;

                //增加列

                for (i = minCol; i <= maxCol; i++)
                {
                    csvDT.Columns.Add(i.ToString());
                }
                for (row = minRow; row <= maxRow; row++)
                {
                    DataRow csvDR = csvDT.NewRow();

                    i = 0;
                    for (col = minCol; col <= maxCol; col++)
                    {
                        csvDR[i] = this[row, col];
                        i++;
                    }
                    csvDT.Rows.Add(csvDR);
                }

                return csvDT;
            }
        }


        /// <summary>
        /// 检查行数是否是有效的

        /// </summary>
        /// <param name="col"></param>  
        private void CheckRowValid(int row)
        {
            if (row <= 0)
            {
                throw new Exception("行数不能小于0");
            }
            if (row > RowCount)
            {
                throw new Exception("没有当前行的数据");
            }
        }

        /// <summary>
        /// 检查最大行数是否是有效的

        /// </summary>
        /// <param name="col"></param>  
        private void CheckMaxRowValid(int maxRow)
        {
            if (maxRow <= 0 && maxRow != -1)
            {
                throw new Exception("行数不能等于0或小于-1");
            }
            if (maxRow > RowCount)
            {
                throw new Exception("没有当前行的数据");
            }
        }

        /// <summary>
        /// 检查列数是否是有效的

        /// </summary>
        /// <param name="col"></param>  
        private void CheckColValid(int col)
        {
            if (col <= 0)
            {
                throw new Exception("列数不能小于0");
            }
            if (col > ColCount)
            {
                throw new Exception("没有当前列的数据");
            }
        }

        /// <summary>
        /// 检查检查最大列数是否是有效的

        /// </summary>
        /// <param name="col"></param>  
        private void CheckMaxColValid(int maxCol)
        {
            if (maxCol <= 0 && maxCol != -1)
            {
                throw new Exception("列数不能等于0或小于-1");
            }
            if (maxCol > ColCount)
            {
                throw new Exception("没有当前列的数据");
            }
        }

        /// <summary>
        /// 载入CSV文件
        /// </summary>
        private void LoadCsvFile()
        {
            //对数据的有效性进行验证

            if (this.fileName == null)
            {
                throw new Exception("请指定要载入的CSV文件名");
            }
            else if (!File.Exists(this.fileName))
            {
                throw new Exception("指定的CSV文件不存在");
            }
            else
            {
            }
            if (this.encoding == null)
            {
                this.encoding = Encoding.Default;
            }

            StreamReader sr = new StreamReader(this.fileName, this.encoding);
            string csvDataLine;

            csvDataLine = "";
            while (true)
            {
                string fileDataLine;

                fileDataLine = sr.ReadLine();
                if (fileDataLine == null)
                {
                    break;
                }
                if (csvDataLine == "")
                {
                    csvDataLine = fileDataLine;//GetDeleteQuotaDataLine(fileDataLine);
                }
                else
                {
                    csvDataLine += "\r\n" + fileDataLine;//GetDeleteQuotaDataLine(fileDataLine);
                }
                //如果包含偶数个引号，说明该行数据中出现回车符或包含逗号
                if (!IfOddQuota(csvDataLine))
                {
                    AddNewDataLine(csvDataLine);
                    csvDataLine = "";
                }
            }
            sr.Close();
            //数据行出现奇数个引号
            if (csvDataLine.Length > 0)
            {
                throw new Exception("CSV文件的格式有错误");
            }
        }

        /// <summary>
        /// 获取两个连续引号变成单个引号的数据行
        /// </summary>
        /// <param name="fileDataLine">文件数据行</param>
        /// <returns></returns>
        private string GetDeleteQuotaDataLine(string fileDataLine)
        {
            return fileDataLine.Replace("\"\"", "\"");
        }

        /// <summary>
        /// 判断字符串是否包含奇数个引号
        /// </summary>
        /// <param name="dataLine">数据行</param>
        /// <returns>为奇数时，返回为真；否则返回为假</returns>
        private bool IfOddQuota(string dataLine)
        {
            int quotaCount;
            bool oddQuota;

            quotaCount = 0;
            for (int i = 0; i < dataLine.Length; i++)
            {
                if (dataLine[i] == '\"')
                {
                    quotaCount++;
                }
            }

            oddQuota = false;
            if (quotaCount % 2 == 1)
            {
                oddQuota = true;
            }

            return oddQuota;
        }

        /// <summary>
        /// 判断是否以奇数个引号开始

        /// </summary>
        /// <param name="dataCell"></param>
        /// <returns></returns>
        private bool IfOddStartQuota(string dataCell)
        {
            int quotaCount;
            bool oddQuota;

            quotaCount = 0;
            for (int i = 0; i < dataCell.Length; i++)
            {
                if (dataCell[i] == '\"')
                {
                    quotaCount++;
                }
                else
                {
                    break;
                }
            }

            oddQuota = false;
            if (quotaCount % 2 == 1)
            {
                oddQuota = true;
            }

            return oddQuota;
        }

        /// <summary>
        /// 判断是否以奇数个引号结尾
        /// </summary>
        /// <param name="dataCell"></param>
        /// <returns></returns>
        private bool IfOddEndQuota(string dataCell)
        {
            int quotaCount;
            bool oddQuota;

            quotaCount = 0;
            for (int i = dataCell.Length - 1; i >= 0; i--)
            {
                if (dataCell[i] == '\"')
                {
                    quotaCount++;
                }
                else
                {
                    break;
                }
            }

            oddQuota = false;
            if (quotaCount % 2 == 1)
            {
                oddQuota = true;
            }

            return oddQuota;
        }

        /// <summary>
        /// 加入新的数据行

        /// </summary>
        /// <param name="newDataLine">新的数据行</param>
        private void AddNewDataLine(string newDataLine)
        {
            //System.Diagnostics.Debug.WriteLine("NewLine:" + newDataLine);

            ////return;

            ArrayList colAL = new ArrayList();
            string[] dataArray = newDataLine.Split(',');
            bool oddStartQuota;        //是否以奇数个引号开始

            string cellData;

            oddStartQuota = false;
            cellData = "";
            for (int i = 0; i < dataArray.Length; i++)
            {
                if (oddStartQuota)
                {
                    //因为前面用逗号分割,所以要加上逗号
                    cellData += "," + dataArray[i];
                    //是否以奇数个引号结尾
                    if (IfOddEndQuota(dataArray[i]))
                    {
                        colAL.Add(GetHandleData(cellData));
                        oddStartQuota = false;
                        continue;
                    }
                }
                else
                {
                    //是否以奇数个引号开始

                    if (IfOddStartQuota(dataArray[i]))
                    {
                        //是否以奇数个引号结尾,不能是一个双引号,并且不是奇数个引号

                        if (IfOddEndQuota(dataArray[i]) && dataArray[i].Length > 2 && !IfOddQuota(dataArray[i]))
                        {
                            colAL.Add(GetHandleData(dataArray[i]));
                            oddStartQuota = false;
                            continue;
                        }
                        else
                        {

                            oddStartQuota = true;
                            cellData = dataArray[i];
                            continue;
                        }
                    }
                    else
                    {
                        colAL.Add(GetHandleData(dataArray[i]));
                    }
                }
            }
            if (oddStartQuota)
            {
                throw new Exception("数据格式有问题");
            }
            this.rowAL.Add(colAL);
        }


        /// <summary>
        /// 去掉格子的首尾引号，把双引号变成单引号

        /// </summary>
        /// <param name="fileCellData"></param>
        /// <returns></returns>
        private string GetHandleData(string fileCellData)
        {
            if (fileCellData == "")
            {
                return "";
            }
            if (IfOddStartQuota(fileCellData))
            {
                if (IfOddEndQuota(fileCellData))
                {
                    return fileCellData.Substring(1, fileCellData.Length - 2).Replace("\"\"", "\""); //去掉首尾引号，然后把双引号变成单引号
                }
                else
                {
                    throw new Exception("数据引号无法匹配" + fileCellData);
                }
            }
            else
            {
                //考虑形如""    """"      """"""   
                if (fileCellData.Length > 2 && fileCellData[0] == '\"')
                {
                    fileCellData = fileCellData.Substring(1, fileCellData.Length - 2).Replace("\"\"", "\""); //去掉首尾引号，然后把双引号变成单引号
                }
            }

            return fileCellData;
        }
        public static bool DataGridViewToCSV(DataGridView dataGridView)
        {
            if (dataGridView.Rows.Count == 0)
            {
                //MessageBox.Show("没有数据可导出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "CSV files (*.csv)|*.csv";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.FileName = null;
            saveFileDialog.Title = "保存";
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                Stream stream = saveFileDialog.OpenFile();
                StreamWriter sw = new StreamWriter(stream, System.Text.Encoding.GetEncoding(-0));
                string strLine = "";
                try
                {
                    //表头
                    for (int i = 0; i < dataGridView.ColumnCount; i++)
                    {
                        if (i > 0)
                            strLine += ",";
                        strLine += dataGridView.Columns[i].HeaderText;
                    }
                    strLine.Remove(strLine.Length - 1);
                    sw.WriteLine(strLine);
                    strLine = "";
                    //表的内容
                    for (int j = 0; j < dataGridView.Rows.Count; j++)
                    {
                        strLine = "";
                        int colCount = dataGridView.Columns.Count;
                        for (int k = 0; k < colCount; k++)
                        {
                            if (k > 0 && k < colCount)
                                strLine += ",";
                            if (dataGridView.Rows[j].Cells[k].Value == null)
                                strLine += "";
                            else
                            {
                                string cell = dataGridView.Rows[j].Cells[k].Value.ToString().Trim();
                                //防止里面含有特殊符号
                                cell = cell.Replace("\"", "\"\"");
                                cell = "\"" + cell + "\"";
                                strLine += cell;
                            }
                        }
                        sw.WriteLine(strLine);
                    }
                    sw.Close();
                    stream.Close();
                    //MessageBox.Show("数据被导出到：" + saveFileDialog.FileName.ToString(), "导出完毕", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return true;

                }
                catch (Exception ex)
                {
                }
            }
            return false;

        }
        public static bool SaveDataSet2CSV(DataSet ds, string path, string fileName)
        {
            try
            {
                //fileFullName = System.IO.Path.Combine(); StreamWriter sw = File.AppendText(fileFullName);
                System.IO.DirectoryInfo fileInfo = new DirectoryInfo(path);
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                //StreamWriter sw = File.AppendText(fileFullName);
                //去除文件的只读属性
                System.IO.File.SetAttributes(path, System.IO.FileAttributes.Normal);
                using (StreamWriter streamWriter = new StreamWriter(path + fileName, false, Encoding.Default))
                {
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        StringBuilder colStr = new StringBuilder();
                        foreach (DataColumn col in ds.Tables[0].Columns)
                        {
                            colStr.Append(col.ToString() + ",");
                        }
                        streamWriter.WriteLine(colStr.ToString());
                        foreach (DataRow row in ds.Tables[0].Rows)
                        {
                            StringBuilder str = new StringBuilder();
                            foreach (DataColumn col in ds.Tables[0].Columns)
                            {
                                str.Append(row[col.Caption.ToString()].ToString() + ",");
                            }
                            streamWriter.WriteLine(str.ToString());
                        }
                    }
                    streamWriter.Flush();
                    streamWriter.Close();
                }
            }
            catch (Exception ex)
            {
                Log.ErrorByTime($"Save Data Set 2 CSV ,catch:{ex.Message}");
                return false;
            }
            return true;
        }
        public static bool SaveDataSet2CSV(DataSet ds)
        {
            try
            {
                if (ds == null)
                {
                    return false;
                }
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Filter = "CSV files (*.csv)|*.csv";
                saveFileDialog.FilterIndex = 0;
                saveFileDialog.RestoreDirectory = true;
                saveFileDialog.CreatePrompt = true;
                saveFileDialog.FileName = null;
                saveFileDialog.Title = "保存";
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    using (StreamWriter streamWriter = new StreamWriter(saveFileDialog.FileName, false, Encoding.Default))
                    {
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            StringBuilder colStr = new StringBuilder();
                            foreach (DataColumn col in ds.Tables[0].Columns)
                            {
                                colStr.Append(col.ToString() + ",");
                            }
                            streamWriter.WriteLine(colStr.ToString());
                            foreach (DataRow row in ds.Tables[0].Rows)
                            {
                                StringBuilder str = new StringBuilder();
                                foreach (DataColumn col in ds.Tables[0].Columns)
                                {
                                    str.Append(row[col.Caption.ToString()].ToString() + ",");
                                }
                                streamWriter.WriteLine(str.ToString());
                            }
                        }
                        streamWriter.Flush();
                        streamWriter.Close();
                    }
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                Log.ErrorByTime($"Save Data Set 2 CSV ,catch:{ex.Message}");
                return false;
            }
            return true;
        }
        public static bool SaveDict2CSV(Dictionary<string, object> dict, string fileName)
        {
            try
            {
                if (dict == null) return false;
                ReaderWriterLockSlim LogWriteLock = new ReaderWriterLockSlim();
                try
                {
                    string path = Path.GetDirectoryName(fileName);
                    System.IO.DirectoryInfo fileInfo = new DirectoryInfo(path);
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    if (!File.Exists(fileName))
                    {
                        using (StreamWriter streamWriter = new StreamWriter(fileName, false, Encoding.UTF8))
                        {
                            StringBuilder str = new StringBuilder();
                            foreach (string key in dict.Keys)
                            {
                                str.Append($"{key},");
                            }
                            streamWriter.WriteLine(str.ToString() ?? "");
                            streamWriter.Flush();
                            streamWriter.Close();
                        }
                    }
                    LogWriteLock.EnterWriteLock();

                    System.IO.File.SetAttributes(fileName, System.IO.FileAttributes.Normal);
                    using (StreamWriter streamWriter = new StreamWriter(fileName, true, Encoding.UTF8))
                    {
                        StringBuilder str = new StringBuilder();
                        foreach (object value in dict.Values)
                        {
                            string temp = value?.ToString();
                            temp = temp.Contains(",") ? $"\"{temp}\"" : temp;
                            str.Append(temp + ",");
                        }
                        streamWriter.WriteLine(str.ToString() ?? "");
                        streamWriter.Flush();
                        streamWriter.Close();
                        return true;
                    }
                }
                catch (Exception ex)
                {
                    Log.ErrorByTime($"Save Dict Result Data 2 CSV ,catch:{ex.Message}");
                    return false;
                }
                finally
                {
                    LogWriteLock.ExitWriteLock();
                }
            }
            catch (Exception ex)
            {
                Log.ErrorByTime($"Save Data Set 2 CSV ,catch:{ex.Message}");
                return false;
            }
        }
        public static bool SaveMESlog2CSV(string log, string csvheader, string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
                return false;
            try
            {
                if (log == null) return false;
                LogWriteLock.EnterWriteLock();
                try
                {
                    string path = Path.GetDirectoryName(fileName);
                    System.IO.DirectoryInfo fileInfo = new DirectoryInfo(path);

                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    if (!File.Exists(fileName))
                    {
                        using (StreamWriter streamWriter = new StreamWriter(fileName, false, Encoding.UTF8))
                        {
                            StringBuilder str = new StringBuilder();
                            str.Append($"{csvheader},");
                            streamWriter.WriteLine(str.ToString() ?? "");
                            streamWriter.Flush();
                            streamWriter.Close();
                        }
                    }

                    {

                        System.IO.File.SetAttributes(fileName, System.IO.FileAttributes.Normal);
                        using (StreamWriter streamWriter = new StreamWriter(fileName, true, Encoding.UTF8))
                        {
                            StringBuilder str = new StringBuilder();
                            str.Append($"{log},");
                            streamWriter.WriteLine(str.ToString() ?? "");
                            streamWriter.Flush();
                            streamWriter.Close();
                        }
                    }
                    return true;
                }
                catch (Exception ex)
                {
                    Log.ErrorByTime($"Save List Result Data 2 CSV ,catch:{ex.Message}");
                    return false;
                }
                finally
                {
                    LogWriteLock.ExitWriteLock();
                }
            }
            catch (Exception ex)
            {
                Log.ErrorByTime($"Save Data Set 2 CSV ,catch:{ex.Message}");
                return false;
            }
        }
        public static bool SaveResultArray2CSV(string[,] listarr, string fileName)
        {
            try
            {
                if (listarr == null || listarr.Length == 0) return false;
                ReaderWriterLockSlim LogWriteLock = new ReaderWriterLockSlim();
                try
                {
                    LogWriteLock.EnterWriteLock();

                    string path = Path.GetDirectoryName(fileName);
                    System.IO.DirectoryInfo fileInfo = new DirectoryInfo(path);
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    if (!File.Exists(fileName))
                    {
                        using (StreamWriter streamWriter = new StreamWriter(fileName, true, Encoding.UTF8))
                        {
                            {
                                StringBuilder str = new StringBuilder();
                                str.Append($"ID,");
                                for (int j = 0; j < listarr.GetLength(1); j++)
                                {
                                    str.Append($"{listarr[0, j]},");
                                }
                                streamWriter.WriteLine(str.ToString().TrimEnd(',') ?? "");
                            }
                            int id = 0;
                            for (int i = 1; i < listarr.GetLength(0); i++)
                            {
                                StringBuilder str = new StringBuilder();
                                str.Append($"{id},");
                                id++;
                                for (int j = 0; j < listarr.GetLength(1); j++)
                                {
                                    str.Append($"{listarr[i, j]},");
                                }
                                streamWriter.WriteLine(str.ToString().TrimEnd(',') ?? "");
                            }
                            streamWriter.Flush();
                            streamWriter.Close();
                            return true;
                        }
                    }
                    else
                    {

                        using (StreamWriter streamWriter = new StreamWriter(fileName, true, Encoding.UTF8))
                        {
                            int id = 0;
                            for (int i = 1; i < listarr.GetLength(0); i++)
                            {
                                StringBuilder str = new StringBuilder();
                                str.Append($"{id},");
                                id++;
                                for (int j = 0; j < listarr.GetLength(1); j++)
                                {
                                    str.Append($"{listarr[i, j]},");
                                }
                                streamWriter.WriteLine(str.ToString().TrimEnd(',') ?? "");
                            }
                            streamWriter.Flush();
                            streamWriter.Close();
                            return true;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.ErrorByTime($"Save List Result Data 2 CSV ,catch:{ex.Message}");
                    return false;
                }
                finally
                {
                    LogWriteLock.ExitWriteLock();
                }
            }
            catch (Exception ex)
            {
                Log.ErrorByTime($"Save Data Set 2 CSV ,catch:{ex.Message}");
                return false;
            }
        }
        public static bool SaveListLocal2CSV<T>(T t, string path, string fileName)
        {
            if (t == null) return false;
            ReaderWriterLockSlim LogWriteLock = new ReaderWriterLockSlim();
            try
            {
                System.IO.DirectoryInfo fileInfo = new DirectoryInfo(path);
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                LogWriteLock.EnterWriteLock();

                System.IO.File.SetAttributes(path, System.IO.FileAttributes.Normal);
                //using (StreamWriter streamWriter = File.AppendText(path + fileName))// new StreamWriter(path + fileName, false, Encoding.Default))
                using (StreamWriter streamWriter = new StreamWriter(path + fileName, false, Encoding.Default))
                {

                    StringBuilder str = new StringBuilder();

                    Type myTypeHead = typeof(T);
                    PropertyInfo[] propertyInfosHead = myTypeHead.GetProperties();
                    foreach (PropertyInfo item in propertyInfosHead)
                    {
                        object obj = item.GetValue(t, null);
                        str.Append($"{obj?.ToString()},");

                    }
                    streamWriter.WriteLine(str.ToString() ?? "");

                    str = new StringBuilder();
                    Type myType = typeof(T);
                    PropertyInfo[] propertyInfos = myType.GetProperties();
                    foreach (PropertyInfo item in propertyInfos)
                    {
                        object obj = item.GetValue(t, null);
                        str.Append($"{obj?.ToString()},");

                    }
                    streamWriter.WriteLine(str.ToString() ?? "");

                    streamWriter.Flush();
                    streamWriter.Close();
                    return true;
                }
            }
            catch (Exception ex)
            {
                Log.ErrorByTime($"Save List LocalData 2 CSV ,catch:{ex.Message}");
                return false;
            }
            finally
            {
                LogWriteLock.ExitWriteLock();
            }
        }
        internal static bool SaveList2CSV<T>(T rd, string path, string fileName = "")
        {
            if (rd == null) return false;
            ReaderWriterLockSlim LogWriteLock = new ReaderWriterLockSlim();
            try
            {
                System.IO.DirectoryInfo fileInfo = new DirectoryInfo(path);
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                LogWriteLock.EnterWriteLock();

                System.IO.File.SetAttributes(path, System.IO.FileAttributes.Normal);
                using (StreamWriter streamWriter = new StreamWriter(path + fileName, false, Encoding.Default))
                {
                    StringBuilder str = new StringBuilder();
                    Type type = typeof(T);
                    List<string> list = type.GetProperties().Select(p => p.Name).ToList();

                    Type myTypeHead = typeof(T);
                    PropertyInfo[] propertyInfosHead = myTypeHead.GetProperties();
                    foreach (PropertyInfo item in propertyInfosHead)
                    {
                        str.Append($"{item.Name},");
                    }
                    streamWriter.WriteLine(str.ToString() ?? "");

                    str = new StringBuilder();
                    Type myType = typeof(T);
                    PropertyInfo[] propertyInfos = myType.GetProperties();
                    foreach (PropertyInfo item in propertyInfos)
                    {
                        object obj = item.GetValue(rd, null);
                        str.Append($"{obj?.ToString()},");

                    }
                    streamWriter.WriteLine(str.ToString() ?? "");

                    streamWriter.Flush();
                    streamWriter.Close();
                    return true;
                }
            }
            catch (Exception ex)
            {
                Log.ErrorByTime($"Save Daoju 2 CSV ,catch:{ex.Message}");
                return false;
            }
            finally
            {
                LogWriteLock.ExitWriteLock();
            }
        }

        internal static bool SaveResult<T>(T t, string path, string fileName)
        {
            if (t == null) return false;
            ReaderWriterLockSlim LogWriteLock = new ReaderWriterLockSlim();
            try
            {
                System.IO.DirectoryInfo fileInfo = new DirectoryInfo(path);
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                    using (StreamWriter streamWriter = new StreamWriter(path + fileName, false, Encoding.Default))
                    {
                        StringBuilder str = new StringBuilder();

                        Type myTypeHead = typeof(T);
                        T tt = System.Activator.CreateInstance<T>();
                        PropertyInfo[] propertyInfosHead = myTypeHead.GetProperties();
                        foreach (PropertyInfo item in propertyInfosHead)
                        {
                            object obj = item.GetValue(tt, null);
                            //str.Append($"{item.Name},");
                            str.Append($"{obj.ToString()},");

                        }
                        streamWriter.WriteLine(str.ToString() ?? "");

                        streamWriter.Flush();
                        streamWriter.Close();
                        //return true;
                    }
                }
                LogWriteLock.EnterWriteLock();

                System.IO.File.SetAttributes(path, System.IO.FileAttributes.Normal);
                //using (StreamWriter streamWriter = File.AppendText(path + fileName))// new StreamWriter(path + fileName, false, Encoding.Default))
                using (StreamWriter streamWriter = new StreamWriter(path + fileName, true, Encoding.Default))
                {
                    StringBuilder str = new StringBuilder();

                    Type myType = typeof(T);
                    PropertyInfo[] propertyInfos = myType.GetProperties();
                    foreach (PropertyInfo item in propertyInfos)
                    {
                        object obj = item.GetValue(t, null);
                        str.Append($"{obj?.ToString()},");

                    }
                    streamWriter.WriteLine(str.ToString() ?? "");

                    streamWriter.Flush();
                    streamWriter.Close();
                    return true;
                }
            }
            catch (Exception ex)
            {
                Log.ErrorByTime($"Save List LocalData 2 CSV ,catch:{ex.Message}");
                return false;
            }
            finally
            {
                LogWriteLock.ExitWriteLock();
            }
        }
        public static bool SaveProductList2CSV(List<string> list, string path, string fileName)
        {
            if (list == null) return false;
            if (list.Count == 0) return true;
            ReaderWriterLockSlim LogWriteLock = new ReaderWriterLockSlim();
            try
            {
                System.IO.DirectoryInfo fileInfo = new DirectoryInfo(path);
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                LogWriteLock.EnterWriteLock();

                System.IO.File.SetAttributes(path, System.IO.FileAttributes.Normal);
                using (StreamWriter streamWriter = File.AppendText(path + fileName))// new StreamWriter(path + fileName, false, Encoding.Default))
                {

                    for (int i = 0; i < list.Count; i++)
                    {
                        StringBuilder str = new StringBuilder();
                        str.Append($"{list[i]}");
                        //str.Append($"\r");
                        streamWriter.WriteLine(str.ToString() ?? "");
                    }
                    streamWriter.Flush();
                    streamWriter.Close();
                    return true;
                }
            }
            catch (Exception ex)
            {
                Log.ErrorByTime($"Save Product 2 CSV ,catch:{ex.Message}");
                return false;
            }
            finally
            {
                LogWriteLock.ExitWriteLock();
            }
        }
        public static bool SaveProductList2CSV(List<string> list, string pathfileName)
        {
            if (list == null) return false;
            if (list.Count == 0) return true;
            try
            {
                // 获取文件名（包含扩展名）
                string fileNameWithExtension = Path.GetFileName(pathfileName);
                // 获取目录路径
                string path = Path.GetDirectoryName(pathfileName);
                System.IO.DirectoryInfo fileInfo = new DirectoryInfo(path);
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                System.IO.File.SetAttributes(path, System.IO.FileAttributes.Normal);
                using (StreamWriter streamWriter = File.AppendText(pathfileName))
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        StringBuilder str = new StringBuilder();
                        str.Append($"{list[i]}");
                        //str.Append($"\r");
                        streamWriter.WriteLine(str.ToString() ?? "");
                    }
                    streamWriter.Flush();
                    streamWriter.Close();
                    return true;
                }
            }
            catch (Exception ex)
            {
                Log.ErrorByTime($"Save Product 2 CSV ,catch:{ex.Message}");
                return false;
            }
            finally
            {
            }
        }
        internal static bool SaveAlarm<T>(T t, string path, string fileName)
        {
            if (t == null) return false;
            try
            {
                Type type = typeof(T);
                PropertyInfo[] property = type.GetProperties();

                System.IO.DirectoryInfo fileInfo = new DirectoryInfo(path);
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                    using (StreamWriter streamWriter = new StreamWriter(path + fileName, false, Encoding.UTF8))
                    {
                        StringBuilder str = new StringBuilder();
                        for (int i = 0; i < property.Length; i++)
                        {
                            DataCalassAttribute customAttribute = property[i].GetCustomAttribute<DataCalassAttribute>();
                            str.Append($"{customAttribute.GetName()},");
                        }
                        streamWriter.WriteLine(str.ToString() ?? "");
                        streamWriter.Flush();
                        streamWriter.Close();
                    }
                }

                System.IO.File.SetAttributes(path, System.IO.FileAttributes.Normal);
                //using (StreamWriter streamWriter = File.AppendText(path + fileName))// new StreamWriter(path + fileName, false, Encoding.Default))
                using (StreamWriter streamWriter = new StreamWriter(path + fileName, true, Encoding.UTF8))
                {
                    StringBuilder str = new StringBuilder();
                    foreach (PropertyInfo item in property)
                    {
                        object obj = item.GetValue(t, null);
                        str.Append($"{obj?.ToString()},");

                    }
                    streamWriter.WriteLine(str.ToString() ?? "");
                    streamWriter.Flush();
                    streamWriter.Close();
                    return true;
                }
            }
            catch (Exception ex)
            {
                Log.ErrorByTime($"Save Alarm 2 CSV ,catch:{ex.Message}");
                return false;
            }
            finally
            {
            }
        }
        /// <summary>
        /// 将 double 数组写入 CSV 文件，以横向显示（逗号分隔）。
        /// </summary>
        /// <param name="filePath">要写入的文件路径。</param>
        /// <param name="data">要写入的 double 数组。</param>
        /// <param name="separator">字段分隔符（默认为逗号）。</param>
        public static bool WriteDoubleArrayToCsv(List<double[]> list, string filePath, string separator = ",")
        {
            if (list == null || list.Count == 0)
            {
                Console.WriteLine("数据数组为空，操作取消。");
                return false;
            }


            //// 使用 LINQ 的 Select 方法将每个 double 元素转换为字符串
            //// 使用 InvariantCulture 确保浮点数的小数点是 '.'，避免受系统区域设置影响（某些系统使用逗号作为小数点）。
            //string[] stringData = data
            //    .Select(d => d.ToString(CultureInfo.InvariantCulture))
            //    .ToArray();

            //// 使用 string.Join() 方法，用指定的分隔符将所有字符串连接成一行
            //// 这就是实现 "横向显示" 的关键步骤
            //string csvLine = string.Join(separator, stringData);

            try
            {
                string path = System.IO.Path.GetDirectoryName(filePath); // 获取文件路径
                string name = System.IO.Path.GetFileName(filePath); // 获取文件名
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                using (StreamWriter writer = new StreamWriter(filePath, true))
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        var item = list[i];
                        string[] stringData = item.Select(d => d.ToString(CultureInfo.InvariantCulture)).ToArray();
                        string csvLine = string.Join(separator, stringData);
                        if (i == 0)
                            writer.WriteLine("控制值：," + csvLine);
                        else
                            writer.WriteLine("反馈值：," + csvLine);
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"写入文件时发生错误: {ex.Message}");
            }
            return false;
        }
        public static bool CreatePath(string filePath)
        {
            try
            {
                string path = System.IO.Path.GetDirectoryName(filePath); // 获取文件路径
                string name = System.IO.Path.GetFileName(filePath); // 获取文件名
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"写入文件时发生错误: {ex.Message}");
            }
            return false;
        }
        /// <summary>
        /// 保存对称位置平均值
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="newData"></param>
        public static void AppendDataToCsvDouble(string filePath, double[] newData)
        {
            // 1. 定义新数据的格式 (假设是逗号分隔)
            // 例如：对于 { "2023-10-25", "150.75", "Processed" }
            // 拼接成 "2023-10-25,150.75,Processed"
            string newCsvLine = "对称位置平均值：," + string.Join(",", newData);

            // 2. 准备要写入文件的完整内容
            // 必须在前面加上 Environment.NewLine 确保它在新的一行
            string contentToAppend = Environment.NewLine + newCsvLine;

            try
            {
                // File.AppendAllText 会自动检查文件是否存在，
                // 如果存在则在末尾追加内容，如果不存在则创建新文件。
                // 使用 UTF8 编码是处理 CSV 文件中文字符的最佳实践。
                File.AppendAllText(filePath, contentToAppend, Encoding.UTF8);

                //Debug.WriteLine($"成功向文件 '{filePath}' 追加了新行: {newCsvLine}");
            }
            catch (Exception ex)
            {
                //Debug.WriteLine($"写入文件时发生错误: {ex.Message}");
            }
        }
    }
}